/*
 * @Author: LC
 * @Date: 2022/3/4
 * @Description:
 */

import { Service } from 'egg';

export default class UserService extends Service {
  async generateToken(data) {
    const { ctx } = this;
    const token = ctx.helper.getToken(data); // token生成
    // await app.redis.set(data.uid + data.email, token, 'ex', 7200); // 保存到redis
    return token;
  }

  async register({ email, password, userName, phone }) {
    const { ctx } = this;
    return ctx.model.User.create({
      email,
      userName,
      phone,
      password: ctx.helper.cryptPwd(password),
    });
  }
  // 查询单个用户判断是否存在数据库
  async findUser({ id, status = 1, userName, phone }) {

    const { ctx, app } = this;
    const Op = app.Sequelize.Op;
    const query: any = { status };
    const query2: any = {};
    userName && (query.userName = userName);
    phone && (query2.phone = phone);
    id && (query.id = id);

    return ctx.model.User.findOne({
      where: { [Op.or]: [ query, query2 ] },
    });
  }

  /**
   * 分页查询
   * @param offset 起始页
   * @param limit 每页展示条数
   * offset=page*limit-limit

  const query = {
  offset: app.toInt(pageNum) * app.toInt(pageSize) - app.toInt(pageSize),
  limit: app.toInt(pageSize)
  };
  return await app.model.Diary.findAndCountAll({ ...query, raw: true });
   */

  async getUsers({ page, pageSize }: any) {
    const where = { status: 1 };
    const { count, rows } = await this.ctx.model.User.findAndCountAll({
      where,
      offset: (page - 1) * pageSize,
      limit: pageSize,
      order: [[ 'createdAt', 'DESC' ]],
    });

    return {
      record: rows,
      currentPage: Number(page),
      pageSize,
      pages: Math.ceil(count / pageSize),
      total: count,
    };
  }

  async queryUserById(id) {
    return this.ctx.model.User.findOne({
      where: { id, status: 1 },
      attributes: [
        'id',
        'userName',
        'email',
        'phone',
        'nickName',
        'avatar',
        'website',
        'github',
        'github',
        'gitee',
        'profession',
        'summary',
        'accountType',
      ],
    });
  }

  async updateAccount(params, id) {
    return this.ctx.model.User.update(params, { where: { id } });
  }
  // 查询单个用户判断是否存在数据库
  async findUserByEmail(email) {
    const { ctx, app } = this;
    const Op = app.Sequelize.Op;
    const query: any = {};
    email && (query.email = email);
    return ctx.model.User.findOne({
      where: { [Op.or]: [ query ] },
    });
  }


  async viewAddOne(id) {
    const { literal } = this.app.Sequelize;
    return this.ctx.model.User.update(
      {
        totalView: literal('total_view + 1'),
      },
      {
        where: { id },
      },
    );
  }
  // 查询用户信息返回角色和菜单信息
  async findUserInfo(id) {
    const { ctx, app } = this;
    const Op = app.Sequelize.Op;
    const query: any = {};
    id && (query.id = id);
    return ctx.model.User.findOne({
      where: { [Op.or]: [ query ] },
      attributes: [
        'id',
        'userName',
        'phone',
        'accountType',
      ],
      include: [
        {
          model: ctx.model.Role,
          attributes: [ 'id', 'name' ],
          through: {
            attributes: [ 'id', 'userId', 'roleId' ],
          },
        },
        {
          model: ctx.model.Menu,
          attributes: [ 'id', 'name', 'path', 'icon', 'component', 'isMenu', 'isShow', 'sort' ],
          through: {
            attributes: [ 'id', 'userId', 'menuId' ],
          },
        },
      ],
    });
  }


}
